﻿using System;
using System.Linq;
using StudentInfo.Security.Utilities;
using System.Data;

namespace StudentInfo.Areas.AccountArea.Services
{
    public class AccountService
    {
        public static Account Get(string accountName, string password)
        {
            var account = GetByName(accountName, true);

            if (account != null)
                if (!Cryptographer.IsValidPassword(password, account.PasswordSalt, account.PasswordKey))
                    return null;

            return account;
        }

        public static Account GetById(Guid id)
        {
            using (var context = new StudentInfoEntities())
            {
                return context.Accounts.FirstOrDefault(s => s.Id == id);
            }
        }

        public static Account GetByName(string accountName, bool activatedOnly = false)
        {
            using (var context = new StudentInfoEntities())
            {
                return context.Accounts.FirstOrDefault(s => s.AccountName == accountName &&
                    s.IsApproved == activatedOnly);
            }
        }

        public static bool IsExistedByName(string accountName)
        {
            using (var context = new StudentInfoEntities())
            {
                return context.Accounts.Any(s => s.AccountName.ToUpper()
                    == accountName.ToUpper());
            }
        }

        public static void Create(Account account)
        {
            using (var context = new StudentInfoEntities())
            {
                context.Accounts.Add(account);
                context.SaveChanges();
            }
        }

        public static void Save(Account account)
        {
            using (var context = new StudentInfoEntities())
            {
                context.Accounts.Attach(account);
                context.Entry(account).State = EntityState.Modified;
                context.SaveChanges();
            }
        }
    }
}